package ldkxingzhe.l365calendar.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.Arrays;
import java.util.Date;

import ldkxingzhe.l365calendar.R;
import ldkxingzhe.l365calendar.activity.AllEditActivity;
import ldkxingzhe.l365calendar.fragment.presenter.SchedulePresenter;
import ldkxingzhe.l365calendar.utils.CalendarUtil;
import ldkxingzhe.l365calendar.widget.dialog.ListAlertDialogFragment;
import ldkxingzhe.l365calendar.widget.dialog.picker.DatePicker;
import ldkxingzhe.l365calendar.widget.dialog.picker.DateTimePicker;

/**
 * 日程规划
 * Created by xingzhe on 16/1/25.
 */
public class ScheduleFragment extends AllEditFragmentBase
        implements SchedulePresenter.PView, HandleFragmentResult {
    @SuppressWarnings("unused")
    private final static String TAG = "ScheduleFragment";

    // UI element
    private EditText editText;
    private CheckBox checkBoxWholeDay;
    private TextView startTime, endTime, categoryText, descText,
            alarmText, alarmValue, repeatDesc;
    private TextView startTimeName, endTimeName;
    private View startTimeLayout, endTimeLayout, categoryLayout, descLayout,
            alarmLayout, addImageLayout, repeatLayout;
    private LinearLayout alarmDetailLayout;
    private SchedulePresenter presenter;

    // REQUEST_CODE
    private static final int REQUEST_CATEGORY = 0;
    private static final int REQUEST_DESCRIPTION = 1;
    private static final int REQUEST_ALARM = 2;
    private static final int REQUEST_REPEAT = 5;

    public static final int REQUEST_PICK_PHOTO = 3;
    public static final int REQUEST_TAKE_PHOTO = 4;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        presenter = new SchedulePresenter();
        presenter.setView(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View resultView = inflater.inflate(R.layout.fragment_schedule_layout, container, false);
        editText = ((EditText)resultView.findViewById(R.id.note_edit_text));
        checkBoxWholeDay = (CheckBox) resultView.findViewById(R.id.checkbox);
        startTime = (TextView) resultView.findViewById(R.id.time_start_text);
        endTime = (TextView) resultView.findViewById(R.id.time_end_text);
        startTimeLayout = resultView.findViewById(R.id.time_start_layout);
        endTimeLayout = resultView.findViewById(R.id.time_end_layout);
        startTimeName = (TextView) resultView.findViewById(R.id.time_start_name);
        endTimeName = (TextView)resultView.findViewById(R.id.time_end_name);
        categoryLayout = resultView.findViewById(R.id.category_layout);
        categoryText = (TextView) categoryLayout.findViewById(R.id.category_text);
        descLayout = resultView.findViewById(R.id.desc_layout);
        descText = (TextView) descLayout.findViewById(R.id.desc_detail_text);
        alarmLayout = resultView.findViewById(R.id.alarm_layout);
        addImageLayout = resultView.findViewById(R.id.add_image_layout);
        alarmDetailLayout= (LinearLayout) alarmLayout.findViewById(R.id.alarm_detail_layout);
        alarmText = (TextView) alarmLayout.findViewById(R.id.alarm_text);
        alarmValue = (TextView) alarmLayout.findViewById(R.id.alarm_desc);
        repeatLayout = resultView.findViewById(R.id.repeat_layout);
        repeatDesc = (TextView) resultView.findViewById(R.id.repeat_desc);
        initData();
        initEditText();
        initMoreLayout(resultView);
        initCheckBox();
        initTimeLayout();
        initCategory();
        initDescLayout();
        initAlarmLayout();
        initAddImageLayout();
        initRepeatLayout();
        return resultView;
    }

    private void initRepeatLayout() {
        repeatLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = getSingleIntent(getString(R.string.repeat_setting), 4);
                intent.putExtra(ScheduleRepeatFragment.REPEAT_TYPE, presenter.getRepeatType());
                startActivityForResult(intent, REQUEST_REPEAT);
            }
        });
    }

    private void initAddImageLayout() {
        addImageLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String[] itemNames = new String[]{
                        getString(R.string.take_photo), getString(R.string.picker_photo)
                };
                ListAlertDialogFragment alertDialogFragment
                        = ListAlertDialogFragment.newInstance(Arrays.asList(itemNames));
                alertDialogFragment.setTargetFragment(ScheduleFragment.this, 2);
                alertDialogFragment.show(getFragmentManager(), "Dialog");
            }
        });
    }

    private void initAlarmLayout() {
        alarmLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = getSingleIntent(getString(R.string.setting_alarm), 2);
                intent.putExtra(ScheduleAlarmFragment.IS_ALL_DAY, getIsWholeDaySchedule());
                intent.putExtra(ScheduleAlarmFragment.START_TIME, presenter.getStartTimeLong());
                startActivityForResult(intent, REQUEST_ALARM);
            }
        });
    }

    private void initDescLayout() {
        descLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startAllEditActivity(getString(R.string.description), 1, REQUEST_DESCRIPTION);
            }
        });
    }

    private void startAllEditActivity(String string, int value, int requestDescription) {
        startActivityForResult(getSingleIntent(string, value), requestDescription);
    }

    @NonNull
    private Intent getSingleIntent(String string, int value) {
        Intent intent = new Intent(getActivity(), AllEditActivity.class);
        intent.putExtra(AllEditActivity.TYPE, AllEditActivity.SINGLE_TAB);
        intent.putExtra(AllEditActivity.TITLE_NAME, string);
        intent.putExtra(AllEditActivity.CLASS_INDEX, value);
        return intent;
    }

    private void initCategory() {
        categoryLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startAllEditActivity(getString(R.string.category), 0, REQUEST_CATEGORY);
            }
        });
    }

    private void initData() {
        presenter.setStartTime(new Date().getTime());
        startTime.setText(CalendarUtil.formatTime(new Date().getTime(), CalendarUtil.TIME_HM));
        endTime.setText(R.string.not_set_data);
        checkBoxWholeDay.setChecked(false);
    }

    private void initTimeLayout() {
        startTimeLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                presenter.onStartTimeClick();
            }
        });
        endTimeLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                presenter.onEndTimeClick();
            }
        });
    }

    private void initCheckBox() {
        checkBoxWholeDay.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                presenter.onIsWholeDayChanged(isChecked);
            }
        });
    }

    private void initMoreLayout(View resultView) {
        View moreBtnLayout = resultView.findViewById(R.id.more_btn_layout);
        final ImageView moreArrow = (ImageView) moreBtnLayout.findViewById(R.id.more_image);
        final View moreLayout = resultView.findViewById(R.id.more_layout);
        moreBtnLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (moreLayout.getVisibility() == View.GONE) {
                    moreArrow.setImageResource(R.drawable.schedule_edit_item_arrow_up);
                    moreLayout.setVisibility(View.VISIBLE);
                } else {
                    moreArrow.setImageResource(R.drawable.schedule_edit_item_arrow_down);
                    moreLayout.setVisibility(View.GONE);
                }
            }
        });
    }

    private void initEditText() {
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                setIsChanged(true);
            }
        });
    }


    @Override
    public void onSaveClick() {
        presenter.onSave();
        getActivity().finish();
    }

    @Override
    public boolean getIsWholeDaySchedule() {
        return checkBoxWholeDay.isChecked();
    }

    @Override
    public String getStartTimeText() {
        return startTime.getText().toString();
    }

    @Override
    public String getEndTimeText() {
        return endTime.getText().toString();
    }

    @Override
    public String getCategoryText() {
        return categoryText.getText().toString().trim();
    }

    @Override
    public String getDescriptionText() {
        return descText.getText().toString().trim();
    }

    @Override
    public String getContentText() {
        return editText.getText().toString().trim();
    }

    @Override
    public void setStartTimeText(String startTimeText) {
        startTime.setText(startTimeText);
    }

    @Override
    public void setEndTimeText(String endTimeText) {
        endTime.setText(endTimeText);
    }

    @Override
    public void showTimePicker(long timeLong, int requestCode){
        FragmentManager manager = getFragmentManager();
        DialogFragment dialogFragment = (DialogFragment) manager.findFragmentByTag("Dialog");
        if(dialogFragment == null){
            if(getIsWholeDaySchedule()){
                dialogFragment = DatePicker.newInstance(timeLong);
            }else{
                dialogFragment = DateTimePicker.newInstance(timeLong);
            }
        }else{
            dialogFragment.dismiss();
        }

        dialogFragment.setTargetFragment(this, requestCode);
        dialogFragment.show(manager, "Dialog");
    }

    @Override
    public void setAlarmDetailLayoutVisibility(int visibility) {
        alarmDetailLayout.setVisibility(visibility);
    }
    @Override
    public void alarmDetailLayoutClear(){
        alarmDetailLayout.removeAllViews();
    }
    @Override
    public void alarmDetailLayoutAddView(String name, String value){
        View resultView = LayoutInflater.from(getActivity())
                .inflate(R.layout.item_left_name_right_value, alarmDetailLayout, false);
        TextView nameText = (TextView) resultView.findViewById(R.id.name);
        TextView valueText = (TextView) resultView.findViewById(R.id.value);
        nameText.setText(name);
        valueText.setText(value);
        alarmDetailLayout.addView(resultView);
    }

    @Override
    public void repeatTextView(String repeatName) {
        repeatDesc.setText(repeatName);
    }

    @Override
    public void alarmLayoutNameValue(String leftName, String rightValue) {
        alarmText.setText(leftName);
        alarmValue.setText(rightValue);
    }


    @Override
    public void onHandleFragmentResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == 0 || requestCode == 1){
            presenter.onHandleTimePickerResult(requestCode, resultCode, data);
        }else if(requestCode == 2){
            presenter.onHandleListAlertResult(resultCode, data);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode == Activity.RESULT_CANCELED) return;
        setIsChanged(true);
        switch (requestCode){
            case REQUEST_CATEGORY:
                categoryText.setText(data.getStringExtra(ScheduleCategoryFragment.RESULT));
                break;
            case REQUEST_DESCRIPTION:
                descText.setText(data.getStringExtra(ScheduleDescriptionFragment.RESULT));
                descText.setVisibility(View.VISIBLE);
                break;
            case REQUEST_PICK_PHOTO:
                presenter.onPickPhotoResult(resultCode, data);
                break;
            case REQUEST_ALARM:
                presenter.onAlarmResult(resultCode, data);
                break;
            case REQUEST_REPEAT:
                presenter.onRepeatResult(resultCode, data);
                break;
            default:
                Log.e(TAG, "onActivityResult, this code should not be executed");
        }
    }
}
